package cn.com.zte.ngbc.dao.mybatis.dynamicsql.node;

import cn.com.zte.common.util.StringUtil;
import cn.com.zte.ngbc.dao.mybatis.dynamicsql.DynamicContext;
import cn.com.zte.ngbc.frw.model.sql.dynamic.DynamicSqlSqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.SqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.StrSqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.WhereSqlNode;
import java.util.List;

public class DynamicSqlSqlNodeHandler
  implements SqlNodeHandler
{
  private DynamicSqlSqlNode sql;
  
  public DynamicSqlSqlNodeHandler(DynamicSqlSqlNode sql)
  {
    this.sql = sql;
  }
  
  public String process(DynamicContext context)
  {
    StringBuilder sqlBuilder = new StringBuilder();
    List<SqlNode> logics = this.sql.getLogicSqlNodes();
    if ((logics == null) || (logics.size() == 0)) {
      throw new IllegalArgumentException("未配置逻辑节点");
    }
    for (SqlNode logic : logics)
    {
      String childSql;
      try
      {
        SqlNodeHandler sqlNodeHandler;
        if ((logic instanceof StrSqlNode))
        {
          sqlNodeHandler = new StrSqlNodeHandler((StrSqlNode)logic);
        }
        else
        {
          if ((logic instanceof WhereSqlNode)) {
            sqlNodeHandler = new WhereSqlNodeHandler((WhereSqlNode)logic);
          } else {
            throw new IllegalArgumentException("不支持该逻辑运算符[" + logic.getClass().getSimpleName() + "]");
          }
        }
        childSql = sqlNodeHandler.process(context);
      }
      catch (Exception e)
      {
        throw new IllegalArgumentException("解析sql的where条件出错 , cause by :" + e.getMessage(), e);
      }
      if (!StringUtil.isEmpty(childSql)) {
        sqlBuilder.append(childSql).append(" ");
      }
    }
    return sqlBuilder.toString().trim();
  }
}